package com.siruier.boss.ui.fragment.order

import android.app.Activity
import android.os.Bundle
import android.view.View
import androidx.core.view.forEach
import androidx.core.view.isVisible
import com.siruier.boss.R
import com.siruier.boss.api.core.launchUI
import com.siruier.boss.api.core.toData
import com.siruier.boss.api.mallApi
import com.siruier.boss.bean.*
import com.siruier.boss.common.handleLoginName
import com.siruier.boss.databinding.FragmentGiftWarehouseListBinding
import com.siruier.boss.databinding.ItemGiftWarehouseBinding
import com.siruier.boss.ui.activity.mall.SelfUseSendActivity
import com.siruier.boss.ui.api.ApiObserver
import com.siruier.boss.ui.cache.UserCache
import com.siruier.boss.ui.dialog.HangingSaleDialog
import com.siruier.boss.ui.dialog.showAlertDialog
import com.siruier.boss.ui.ext.textSpan
import com.siruier.boss.ui.ext.toColor
import com.siruier.boss.ui.ext.toastMessageLong
import com.siruier.boss.ui.helper.InjectBundle
import com.siruier.boss.ui.helper.ShareHelper
import com.siruier.boss.ui.listener.OnTabSelectedListener
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

class GiftWarehouseReceiveRvFragment : GiftWarehouseListFragment<FragmentGiftWarehouseListBinding>() {
    companion object {
        fun newInstance(stateEnum: GiftWarehouseReceiveStateEnum): GiftWarehouseReceiveRvFragment {
            return GiftWarehouseReceiveRvFragment().apply {
                arguments = Bundle().apply {
                    putParcelable("stateEnum", stateEnum)
                }
            }
        }
    }

    private val selfUseStateEnum = GiftWarehouseReceiveSelfUseStateEnum.values()
    private val passOnStateEnum = GiftWarehouseReceivePassOnStateEnum.values()
    private val hangingSaleStateEnum = GiftWarehouseReceiveHangingSaleStateEnum.values()
    private val stateEnum: GiftWarehouseReceiveStateEnum by InjectBundle()
    private var giveStatus: Int? = null
    private var ownStatus: Int? = null
    private var saleStatus: Int? = null

    override fun initView(rootView: View?, savedInstanceState: Bundle?) {
        vb.tabLayout.isVisible = stateEnum != GiftWarehouseReceiveStateEnum.WAIT_HANDLE
        when (stateEnum) {
            GiftWarehouseReceiveStateEnum.SELF_USE -> {
                selfUseStateEnum.forEach { state ->
                    vb.tabLayout.addTab(vb.tabLayout.newTab().setText(state.stateName))
                }
                giveStatus = selfUseStateEnum[0].state
                vb.tabLayout.addOnTabSelectedListener(OnTabSelectedListener {
                    giveStatus = selfUseStateEnum[it.position].state
                    mRefreshHelper.onRefresh()
                })
            }
            GiftWarehouseReceiveStateEnum.PASS_ON -> {
                passOnStateEnum.forEach { state ->
                    vb.tabLayout.addTab(vb.tabLayout.newTab().setText(state.stateName))
                }
                ownStatus = passOnStateEnum[0].state
                vb.tabLayout.addOnTabSelectedListener(OnTabSelectedListener {
                    ownStatus = passOnStateEnum[it.position].state
                    mRefreshHelper.onRefresh()
                })
            }
            GiftWarehouseReceiveStateEnum.HANGING_SALE -> {
                hangingSaleStateEnum.forEach { state ->
                    vb.tabLayout.addTab(vb.tabLayout.newTab().setText(state.stateName))
                }
                saleStatus = hangingSaleStateEnum[0].state
                vb.tabLayout.addOnTabSelectedListener(OnTabSelectedListener {
                    saleStatus = hangingSaleStateEnum[it.position].state
                    mRefreshHelper.onRefresh()
                })
            }
            GiftWarehouseReceiveStateEnum.WAIT_HANDLE -> {

            }
        }
        super.initView(rootView, savedInstanceState)
        mGiftWarehouseAdapter.setOnClickAdapterListenter(::onClick)
    }

    override fun onReload() {
        launchUI({
            mallApi.receiveOrder(stateEnum.state, giveStatus, ownStatus, saleStatus, mRefreshHelper.page)
                .toData()?.records
        }, mRefreshHelper.handApiObserver())
    }

    private fun onClick(view: View, position: Int) {
        val bean = mGiftWarehouseAdapter.getItem(position)
        launchUI({
            when (view.id) {
                R.id.button_hanging_sale -> {
                    val recoverPrice = mallApi.preSale(bean.orderSn).toData()
                    val sale = suspendCancellableCoroutine<Boolean> { coroutine ->
                        HangingSaleDialog(requireContext(), recoverPrice?.recoverPrice ?: "", bean,
                            {
                                coroutine.resume(false)
                            }, {
                                coroutine.resume(true)
                            })
                            .show()
                    }
                    if (sale) {
                        mallApi.sale(bean.orderSn).toData()
                        "已提交挂卖".toastMessageLong()
                    }
                    sale
                }
                R.id.button_cancel_hanging_sale -> {
                    val cancelSale = suspendCancellableCoroutine<Boolean> { coroutine ->
                        showAlertDialog {
                            mCancelable = false
                            message(message = "确定取消挂卖吗？")
                            negativeButton { coroutine.resume(false) }
                            positiveButton { coroutine.resume(true) }
                        }
                    }
                    if (cancelSale) {
                        mallApi.cancelSale(bean.orderSn).toData()
                        "取消挂卖成功".toastMessageLong()
                    }
                    cancelSale
                }
                R.id.button_pass_on -> {
                    val goods = bean.goodsList[0]
                    ShareHelper.orderTransfer(
                        mThis, vb.viewOrderTransfer, goods.picUrl, goods.goodsName, goods.vipPriceDesc,
                        goods.marketPriceDesc, bean.orderSn
                    )
                    true
                }
                R.id.button_delivery -> {
                    suspendCancellableCoroutine { coroutine ->
                        launchStartActivityForResult(
                            SelfUseSendActivity::class.java, isNeedResultOk = false, options = {
                                putString("mOrderSn", bean.orderSn)
                            }) {
                            coroutine.resume(it.resultCode == Activity.RESULT_OK)
                        }
                    }
                }
                else -> false
            }
        }, ApiObserver(requireContext(), showLoadingDialog = false) {
            if (true == it) {
                mRefreshHelper.onRefresh()
            }
        })
    }

    override fun onBindViewHolder(vb: ItemGiftWarehouseBinding, bean: GiftOrderDetailBean, position: Int) {
        //vb.tvState.text = GiftWarehouseSendFragment.stateEnumMap[bean.status]?.stateName ?: ""
        bean.goodsList.takeIf { it.size > 0 }?.get(0)?.apply {
            vb.tvGoodsMoney.textSpan("市场价${vipPriceDesc}") {
                spanText = vipPriceDesc
                addForegroundColorSpan(R.color.main_color.toColor())
            }
        }
        vb.llButton.forEach { it.isVisible = false }
        when {
            bean.giveDealStatus == GiftWarehouseReceiveStateEnum.WAIT_HANDLE.state -> {
                vb.buttonHangingSale.isVisible = bean.goodsType !in 2..3
                vb.buttonPassOn.isVisible = bean.goodsType !in 2..3
                vb.buttonDelivery.isVisible = true
            }
            bean.giveDealStatus == GiftWarehouseReceiveStateEnum.HANGING_SALE.state &&
                    bean.saleStatus == GiftWarehouseReceiveHangingSaleStateEnum.ON_SALE.state -> {
                vb.buttonCancelHangingSale.isVisible = bean.goodsType !in 2..3
            }
        }
        mGiftWarehouseAdapter.setViewClick(
            position, vb.buttonHangingSale, vb.buttonPassOn, vb.buttonDelivery,
            vb.buttonCancelHangingSale
        )
    }
}